<?php
namespace app\index\controller;
use Firebase\JWT\JWT;
use think\Cache;
use think\Controller;

class Login extends Controller
{
    public function __construct()
    {
        header("Access-Control-Allow-Origin: *");//允许跨域
        header('Content-type: application/json');
        header("Access-Control-Allow-Methods:POST");
        header("access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept,WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token,authorization");

        if (!request()->isPost()) {
            echo refuseVisit();die;
        }
    }

    /**
     * 用户注册 调用接口需传入邮件验证码
     */
    public function register()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('Login');
        if(!$validate->scene('register')->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        $checkCode = Cache::get($data['us_email']);

        if (!$checkCode) {
            $info['code']    = 400;
            $info['message'] = '验证码失效，请重新获取';
            echo displayJson($info);die;
        }

        if (trim($data['code']) !== $checkCode) {
            $info['code']    = '400';
            $info['message'] = '验证码错误';
            echo displayJson($info);die;
        }

        //插入数据
        $data['us_password']    = md5($data['us_password'].'SecretIndex');
        $data['us_create_time'] = time();
        $data['us_image']       = 'http://www.taoerhuo.top/bishe/public/image/index/default.png';
        unset($data['code']);

        //助手函数添加，加入第三个参数false则为单例连接数据库，不会每次都重连数据库
        if (db('user',[],false)->insert($data) !== false) {
            //删除Redis数据
            Cache::rm($data['us_email']);

            $info['code']    = '200';
            $info['message'] = '注册成功,请登录';
            echo displayJson($info);die;
        } else {
            $info['code']    = '400';
            $info['message'] = '注册失败';
            echo displayJson($info);die;
        }
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $data = input('post.');

        $data['account']     = htmlspecialchars($data['account']);
        $data['us_password'] = htmlspecialchars($data['us_password']);

        //校验数据
        $validate = \think\Loader::validate('Login');
        if(!$validate->scene('login')->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        $row = db('user',[],false)->where('us_email',$data['account'])->find();

        if (!empty($row)) {

            if ($row['us_status'] == '2') {
                $info['code']    = '401';
                $info['message'] = '您被禁止使用此平台，如有疑问，请联系管理员';
                echo displayJson($info);die;
            }

            //验证密码
            if ($row['us_password'] == md5($data['us_password'].'SecretIndex')) {
                $info['code']    = '200';
                $info['message'] = '登录成功';
                $info['uid']     = $row['us_id'];
                $info['account'] = $data['account'];
                $info['username']= $row['us_username'];
                $info['image']   = $row['us_image'];
                $info['jwt']     = self::createJwt($row['us_id']);  //生成jwt
                echo displayJson($info);die;
            } else {
                $info['code']    = '400';
                $info['message'] = '密码错误';
                echo displayJson($info);die;
            }
        } else {
            $info['code']    = '400';
            $info['message'] = '该用户不存在';
            echo displayJson($info);die;
        }
    }

    /**
     * 忘记密码 重置密码
     */
    public function resetPwd()
    {
        $data = input('post.');

        //校验数据
        $validate = \think\Loader::validate('Login');
        if(!$validate->scene('resetPwd')->check($data)){
            $info = array('code' => '400','message'=>$validate->getError());
            echo displayJson($info);die;
        }

        //验证邮箱是否存在
        $get_email = db('user',[],false)->where('us_email',$data['us_email'])->find();

        if ($get_email) {

            if ($get_email['us_status'] == '2') {
                $info['code']    = '400';
                $info['message'] = '此邮箱已列入黑名单';
                echo displayJson($info);die;
            }

            //判断用户输入验证码是否正确
            $checkCode = Cache::get($data['us_email']);

            if (!$checkCode) {
                $info['code']    = 400;
                $info['message'] = '验证码失效，请重新获取';
                echo displayJson($info);die;
            }

            if (trim($data['code']) == $checkCode) {
                //执行修改密码
                $newPwd = md5($data['us_password'].'SecretIndex');
                $res    = db('user',[],false)->where('us_email',$data['us_email'])->setField('us_password',$newPwd);

                if ($res >= 0) {
                    //删除Redis数据
                    Cache::rm($data['us_email']);
                    
                    $info['code']    = 200;
                    $info['message'] = '修改密码成功';
                    echo displayJson($info);die;
                } else {
                    $info['code']    = 400;
                    $info['message'] = '修改密码失败';
                    echo displayJson($info);die;
                }
            } else {
                $info['code']    = 400;
                $info['message'] = '验证码错误';
                echo displayJson($info);die;
            }
        } else {
            $info['code']    = 400;
            $info['message'] = '此邮箱尚未注册，请检查后重试';
            echo displayJson($info);die;
        }
    }

    /**
     * 注册发送邮件 (验证码Redis存储)
     */
    public function send_email()
    {
        $data = input('post.');

        if (!isset($data['type'])) {
            $info['code']    = '400';
            $info['message'] = '邮件类型错误';
            echo displayJson($info);die;
        }

        if ($data['type'] == 'reset') {
            //校验数据
            $validate = \think\Loader::validate('Login');
            if(!$validate->scene('reset')->check($data)){
                $info = array('code' => '400','message'=>$validate->getError());
                echo displayJson($info);die;
            }
            //重置密码用 判断邮箱是否存在
            $get_email = db('user',[],false)->where('us_email',$data['us_email'])->find();

            if (!$get_email) {
                $info['code']    = '400';
                $info['message'] = '此邮箱尚未注册，请检查后重试';
                echo displayJson($info);die;
            }
            if ($get_email['us_status'] == '2') {
                $info['code']    = '400';
                $info['message'] = '此邮箱已列入黑名单';
                echo displayJson($info);die;
            }
        } elseif ($data['type'] == 'register') {
            //校验数据
            $validate = \think\Loader::validate('Login');
            if(!$validate->scene('send')->check($data)){
                $info = array('code' => '400','message'=>$validate->getError());
                echo displayJson($info);die;
            }
        } else {
            $info['code']    = '400';
            $info['message'] = 'type标识错误';
            echo displayJson($info);die;
        }

        $code      = make_Verification_Code(6);
        $send_data = array(
            'to_email'   =>$data['us_email'],
            'content'    =>'【淘二货】欢迎使用校内二手物品交易平台，您此次的验证码为：<span style="font-size: 24px;font-weight: bold;"> '.$code.' </span>，请在10分钟内完成验证'
        );

        $send      = sendEmail($send_data);

        if (!$send) {
            $info['code']    = '400';
            $info['message'] = '邮件发送失败';
            echo displayJson($info);die;
        } else {
            $check_code = explode(' ',$send_data['content']);

            // 设置redis
            $options = ['type'  => 'Redis']; //指定类型
            Cache::init($options);//初始化
            Cache::set($data['us_email'],$check_code['4'],600); //redis key有效期为10分钟

            $info['code']         = '200';
            $info['message']      = '邮件发送成功';
            echo displayJson($info);die;
        }
    }

    /**
     * 生成jwt
     * @param $userId
     * @return string
     */
    public function createJwt($userId)
    {
        $key    = md5('taoerhuo'); //jwt的签发密钥，验证token的时候需要用到
        $time   = time(); //签发时间
        $expire = $time + 604800; //过期时间(7天)
        $token  = array(
            "us_id" => $userId,
            "iss" => "http://taoerhuo.top",//签发组织
            "aud" => "YeWenHao", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );

        $jwt = JWT::encode($token, $key);
        return $jwt;
    }



}
